package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.system.LoginLog;
import com.qingcheng.service.system.LoginLogService;
import com.qingcheng.util.WebUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;

/**
 * 登录成功处理器
 *
 * @author 岳剑飞
 * @Company http://www.ithiema.com
 */
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Reference
    private LoginLogService loginLogService;   //登录日志

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //登录后会调用

        String loginName = authentication.getName();  //当前登录用户
        String ip = httpServletRequest.getRemoteAddr(); //获取访问的ip
        LoginLog loginLog = new LoginLog(); //登录日志
        loginLog.setLoginName(loginName);
        loginLog.setIp(ip);
        loginLog.setLoginTime(new Date());  //当前登录时间

        loginLog.setLocation(WebUtil.getCityByIP(ip));//保存城市信息

        String agent = httpServletRequest.getHeader("user-agent");
        loginLog.setBrowserName(WebUtil.getBrowserName(agent));
        loginLogService.add(loginLog);

        httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/main.html");
    }
}
